package org.ly.uap.client.proxy;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.ly.uap.client.util.CommonUtils;
import org.ly.uap.client.util.XmlUtils;

public final class Cas20ProxyRetriever
        implements ProxyRetriever {
    private static final long serialVersionUID = 560409469568911791L;
    private final Log log = LogFactory.getLog(getClass());
    private final String casServerUrl;
    private final String encoding;

    public Cas20ProxyRetriever(String casServerUrl, String encoding) {
        CommonUtils.assertNotNull(casServerUrl, "casServerUrl cannot be null.");
        this.casServerUrl = casServerUrl;
        this.encoding = encoding;
    }

    public String getProxyTicketIdFor(String proxyGrantingTicketId, String targetService) {
        String url = constructUrl(proxyGrantingTicketId, targetService);
        String response = CommonUtils.getResponseFromServer(url, this.encoding);
        String error = XmlUtils.getTextForElement(response, "proxyFailure");

        if (CommonUtils.isNotEmpty(error)) {
            this.log.debug(error);
            return null;
        }

        return XmlUtils.getTextForElement(response, "proxyTicket");
    }

    private String constructUrl(String proxyGrantingTicketId, String targetService) {
        try {
            return this.casServerUrl + (this.casServerUrl.endsWith("/") ? "" : "/") + "proxy" + "?pgt=" +
                    proxyGrantingTicketId + "&targetService=" +
                    URLEncoder.encode(targetService, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }

    }
}





